<template>
  <view>
      <view style="padding: 8rpx 0 8rpx 22rpx;font-size: 24rpx;font-weight: bold;">
          <text>如未找到对应数据，请先对非外市电电力电缆进行申领、出库操作！</text>
          <view style="width: 92%;text-align:right;position: relative;">
              <text style="font-size: 22rpx;color: #007AFF">
                  <text @click="illustrate">贴签说明</text>
                  <image style="width: 32rpx;height: 32rpx;position:absolute;top:12rpx;right: -32rpx" src="@/static/imges/wenhaoer.png" mode=""></image>
              </text>
          </view>
      </view>
      <uni-collapse>
          <view v-for="(item, index) in dataList" :key="index">
              <uni-collapse-item
                  class="collapseStyle"
                  title-border="none"
                  :border="true"
                  v-if="!(+item.needLabelAmount===0&&+item.scanConfirmAmount===0&&+item.needScanConfirmAmount===0)"
              >
                  <template v-slot:title>
                      <view class="type">
                          <text :selectable="true"> {{ item.categoryName }}</text>
                      </view>
                      <view class="type">
                          物料编码：
                          <text :selectable="true">{{ item.categoryCode }}</text>
                      </view>
                      <view style="display: flex;align-items: center;justify-content: space-between;margin-top: 0rpx;position: relative;">
                          <view class="type" style="margin-right: 129rpx">需赋码贴签数量：
                              <text style="font-weight: bold">{{item.needLabelAmount }}</text>
                          </view>
                          <button v-if="+item.labelButton===1"
                                  @click.stop="() => toLabel(item)"
                                  style="margin: 0 30rpx 0 0; padding: 0 10rpx;width: 140rpx;height: 60rpx;font-size: 26rpx;position: absolute;right:0;top: -10rpx;"
                                  type="warn"
                                  :plain="true"
                                  size="mini"
                          >
                              赋码贴签
                          </button>
                          <view style="width: 150rpx" v-else></view>
                      </view>
                      <view style="display: flex;align-items: center;justify-content: space-between;">
                          <view class="type" style="margin-right: 20rpx">
                              已到货确认数量：
                              <text style="font-weight: bold">{{item.scanConfirmAmount}}</text>
                          </view>
                          <view class="type" style="margin-right: 20rpx">
                              待到货确认数量：
                              <text style="font-weight: bold">{{item.needScanConfirmAmount }}</text>
                          </view>
                      </view>
                      <view class="type" style="margin-right: 20rpx">
                          供应商名称：
                          <text style="font-weight: bold">{{item.supplierName }}</text>
                      </view>
                      <view class="type" style="margin-right: 129rpx;width: 100%;">
                          出库明细编号：
                          <text style="font-weight: bold">{{item.osDetailId }}</text>
                      </view>
                      <view style="display: flex;align-items: center;justify-content: space-between;margin-bottom: 10rpx;position: relative;">
                          <view class="type" style="margin-right: 129rpx">绑定数量(米)：
                              <text style="font-weight: bold">{{item.bindAmount }}</text>
                          </view>
                          <button v-if="(manageMode === '31' || manageMode === '04') && item.canCut && +item.bindAmount > 0"  @click.stop="() => editNum(item)"
                                  style="margin: 0 30rpx 0 0; padding: 0 10rpx;width: 180rpx;height: 60rpx;font-size: 26rpx;position: absolute;right:0;top: -10rpx;"
                                  type="warn"
                                  :plain="true"
                                  size="mini"
                          >
                              修改绑定数量
                          </button>
                      </view>
                  </template>
                  <view class="content" style="height: auto">
                      <view style="width: 100%;" v-if="item.sourceAssetCode && item.labelId">
                          <view @click="changeArrow(index)" style="width: 100%;background-color: white;padding: 5rpx 10rpx;margin-bottom: 0rpx;border-radius:6rpx;display: flex;justify-content: space-between;">
                              <view style="display: flex;font-size: 30rpx;font-weight:bold;">
                                  <view style="width: 12rpx; height: 40rpx;background-color: #EB4B4B;margin-top: 8rpx;border-radius:6rpx;margin-right: 12rpx"></view>
                                  {{+item.scanConfirm ===0 ? '未确认':'已确认'}}
                              </view>
                              <view style="width: 80rpx;height: 50rpx;margin-top: 5rpx;">
                                  <image style="left: 20rpx;width: 30rpx;height: 30rpx;" :src="item.arrow?require('@/static/imges/up.png'):require('@/static/imges/down.png')"></image>
                              </view>
                          </view>
                          <view v-if="item.arrow">
                              <u-table :th-style="{ height: '300px' }">
                                  <u-tr>
                                      <u-th width="32%">资源资产编码</u-th>
                                      <u-th width="30%">标签ID</u-th>
                                      <u-th aling="center">操作</u-th>
                                  </u-tr>
                                  <u-tr>
                                      <u-td width="32%" style="width: 20%; overflow: hidden">
                                          <text :selectable="true">{{item.sourceAssetCode || "无" }}</text>
                                      </u-td>
                                      <u-td width="30%" style="width: 33.3%; overflow: hidden">
                                          <text :selectable="true" style="color: #007AFF;" @click="jumpLabelId(item.sourceAssetCode,item.labelId)">
                                              {{ item.labelId }}
                                          </text>
                                      </u-td>
                                      <u-td width="38%">
                                          <view style="text-align: center; box-sizing: border-box;display:flex;justify-content: space-evenly;">
                                              <view v-if="+item.unBindLableButton===1" @click="unbindLabel(item)" class="unbindLabelStyle">
                                                  解绑标签
                                              </view>
                                              <view v-if="+item.swapButton===1" @click.stop="toSignChange(item)" class="unbindLabelStyle">
                                                  换签
                                              </view>
                                              <view v-if="+item.unBindSiteButton===1" @click.stop="() => unbindSite(item)" class="unbindLabelStyle">
                                                  解绑站址
                                              </view>
                                              <text v-if="+item.unBindLableButton===0 && +item.swapButton===0 && +item.unBindSiteButton===0">无</text>
                                          </view>
                                      </u-td>
                                  </u-tr>
                              </u-table>
                          </view>
                      </view>
                  </view>
              </uni-collapse-item>
          </view>
      </uni-collapse>
      <EditNumModal @close="()=>{ showEditNumModal=false}" @confirm="editNumCon" v-if="showEditNumModal" ref="editNumModalRef"></EditNumModal>
      <!-- 解绑模式弹框 -->
      <u-modal v-model="isShowUnbindModal" title="解绑确认" confirm-text="取消" confirm-color="#eb4b4b"
               :title-style="{fontWeight:'bold',fontSize:'40rpx'}" ref="uModal">
          <view class=""
                style="color: #eb4b4b;text-align: center;border: 1px solid #F2F2F2;height: 100rpx;line-height: 100rpx;font-size: 30rpx;">
              <text v-debounce="() => modalClick('01')">解绑（原标签保留)</text>
          </view>
          <view class=""
                style="color: #eb4b4b;text-align: center;border: 1px solid #F2F2F2;height: 100rpx;line-height: 100rpx;font-size: 30rpx;">
              <text v-debounce="() => modalClick('02')">解绑（原标签遗失或破损）</text>
          </view>
      </u-modal>
      <u-popup v-model="bottomShow" mode="bottom" ref="uPopup">
          <view style="height: 300rpx;">
              <view v-debounce="() => getCamera()"
                    style="width: 100%;height: 100rpx;border-bottom: 1px solid #D3D3D3;line-height: 100rpx;padding-left:46% ;">
                  <text style="font-size: 30rpx;">扫码</text>
              </view>
              <view v-debounce="() => getSelectImg()"
                    style="width: 100%;height: 100rpx;border-bottom: 1px solid #D3D3D3;line-height: 100rpx;padding-left:46% ;">
                  <text style="font-size: 30rpx;">相册</text>
                  <text style="font-size: 24rpx;color: #EB4B4B;">(建议照片不得超过4M)</text>
              </view>
              <view @click="canceler()"
                    style="width: 100%;height: 100rpx;border-bottom: 1px solid #D3D3D3;line-height: 100rpx;padding-left:46% ;">
                  <text style="font-size: 30rpx;">取消</text>
              </view>
          </view>
      </u-popup>
  </view>
</template>
<script>

import {getGPS} from "@/inspur/utils/gpsUtil";
import EditNumModal from "@/inspur/completionConfirmation/components/editNumModal.vue";
import {dialogBody} from "@/inspur/utils/getIframeDom";
import qrcode from "@/static/reqrcode";

export default {
  name: "NonExternalPower",
  components: {EditNumModal},
  props: {
      showPhoto:{
          type:Boolean,
          default:false
      },
      titleList:{
          type:Object,
          default:()=>({})
      },
      manageMode:{
          type:String,
      }
  },
  data() {
    return {
        showEditNumModal:false,
        dataList:[],
        isShowUnbindModal:false,
        selectItem:{},
        bottomShow:false,
        bes64: "",
        scanWord: "",
        scanWorderty: "",
        scanWordertytyu: "",
    }
  },
  mounted() {
      this.getNonPowerList();
      const contentBody = window.top.document.body
      this.$nextTick(()=>{
          const uModal = this.$refs.uModal.$el
          const uPopup = this.$refs.uPopup.$el
          contentBody.appendChild(uModal)
          contentBody.appendChild(uPopup)
      })
  },
  methods: {
      getNonPowerList(){
          this.dataList=[];
          this.$axios.get('/material/api/cableMateLabel/queryCableList',{prjId:this.titleList.prjId}).then((res)=>{
              if(res.data && res.data.length>0){
                  res.data.forEach((item)=>{
                      this.dataList.push({
                          ...item,
                          arrow:false,
                      })
                  })
              }
          })
      },
      illustrate(){
          uni.navigateTo({
              url: './illustrate'
          });
      },
      // 展开收齐
      changeArrow(index) {
          this.dataList[index].arrow=!this.dataList[index].arrow
      },
      //解绑标签
      unbindLabel(item){
            // this.isShowUnbindModal=true;
            // this.selectItem=JSON.parse(JSON.stringify(item));
            const params={
              labelId: item.labelId,
              osDetailId: item.osDetailId,
              prjId: this.titleList.prjId,
              resourceAssetCode: item.sourceAssetCode,
              unBindingReason: '01'
            }
            let that=this;
            //解绑标签
            this.$axios.post('/material/api/cableMateLabel/unbindCableLabel',params).then(()=>{
              uni.showModal({
                  confirmColor: '#eb4b4b',
                  title: '温馨提示',
                  content: "解绑成功",
                  showCancel: false,
                  success: () => {
                      that.getNonPowerList();
                      // that.selectItem=JSON.parse(JSON.stringify({}));
                  }
              })
            })
      },
      modalClick(reason){
          this.isShowUnbindModal=false;
          //不需要弹窗 默认理由为01
      },
      //标签跳转经分系统
      jumpLabelId(sourceAssetCode,labelId){
          this.$axios.get('/material/api/pub/material/getOtherSysIpAndPort',{ sysCode:'jingFenSysIpAndPort'}).then((res)=>{
              imp.iWindow.open({url:`${res.data}/api/user/getRedirectToBcsystem?resourceAssetCode=${sourceAssetCode}&elabelNum=${labelId}`})
          })
      },
      //赋码贴签
      toLabel(item){
          let that=this;
          imp.iBarCode.scan(function (result) {
              //直接调用接口
              getGPS(result, item, that.scanLabel);
          });
      },
      scanLabel(result, item,latitude, longitude){
          let that = this;
          let latituder = parseFloat(latitude).toFixed(6);
          let longituder = parseFloat(longitude).toFixed(6);
          let prjCodeer = this.titleList.prjCode || this.titleList.subPrjCode;
          const params={
              labelId: result,
              osDetailId: item.osDetailId,
              prjId: this.titleList.prjId,
              categoryCode: item.categoryCode,
          }
          that.$axios.post('/material/api/cableMateLabel/assignCableLabel',params).then((res)=>{
              that.getNonPowerList();
              //赋码贴签之后，自动跳到到货确认详情页
              uni.navigateTo({
                  url: "../scanOut/detail?item=" +
                      encodeURIComponent(JSON.stringify(res.data)) +
                      "&flag=4&fushuuser=true&prjCodeer=" + prjCodeer+'&latitude='+latituder+'&longitude='+longituder+'&routeType=nonPower&manageMode='+that.manageMode,
              });
          })
      },
      //修改绑定数量
      editNum(item){
          this.showEditNumModal=true;
          this.selectItem=JSON.parse(JSON.stringify(item));
          dialogBody('editNumModalRef',this)
      },
      editNumCon(data){
          //修改绑定数量调到货确认的接口
          let that=this;
          this.showEditNumModal=false
          const params={
              labelId:this.selectItem.labelId,
              osDetailId:this.selectItem.osDetailId,
              prjId:this.titleList.prjId,
              resourceAssetCode:this.selectItem.sourceAssetCode,
              oldAmount:this.selectItem.bindAmount,
              categoryCode: this.selectItem.categoryCode,
              bundingAmount:data,
          }
          this.$axios.post('/material/api/cableMateLabel/scanConfirmCabel',params).then(()=>{
              uni.showModal({
                  confirmColor: '#eb4b4b',
                  title: '温馨提示',
                  content: '修改成功！',
                  showCancel: false,
                  success: () => {
                      that.getNonPowerList();
                      that.selectItem=JSON.parse(JSON.stringify({}));
                  }
              })
          })
      },
      // 跳转换签页面
      toSignChange(item) {
          let that=this;
          const labelCode={
              labelId:item.labelId,
              resourceAssetCode:item.sourceAssetCode
          }
          uni.showModal({
              confirmColor: '#eb4b4b',
              title: "温馨提示",
              content: "除标签丢失、无法扫码识别、标签类型错误、质保期内更换实物外，厂家源头贴码物资禁止随意更换标签，铁塔公司将对不按规定换签的施工单位通报考核。请再次核实本次换签是否合规。",
              success:(res)=>{
                  if(res.confirm){
                      uni.navigateTo({
                          url:
                              "/inspur/changeLabel/changeLabelCheck?item=" +
                              encodeURIComponent(JSON.stringify(item)) +
                              "&item1=" +
                              encodeURIComponent(JSON.stringify(labelCode)) + "&item2=" + encodeURIComponent(JSON.stringify(that.titleList))+'&index=4&prjId='+that.titleList.prjId,
                      });
                      window.TDAPP.onEvent("换签按钮");
                  }else{
                      console.log('取消操作')
                  }
              }
          });
      },
      //到货确认
      scanConfirm(){
          this.bottomShow=true;
          this.bes64 = "";
          this.scanWorderty = "";
          this.scanWordertytyu = "";
      },
      //到货确认扫码
      getCamera(){
          this.bottomShow = false
          window.TDAPP.onEvent("详情页到货确认按钮");
          imp.iBarCode.scan((labelId) => {
              //直接调用接口
              getGPS(labelId, '1', this.scanCodeInfo);
          });
      },
      //相册
      getSelectImg(){
          this.bottomShow = false
          let that = this
          var option = {
              quality: 86,
              encodingType: imp.iCamera.EncodingType.JPEG,
              sizeLimit: 1024 * 100,
              num: 1,
          };

          var failed = () => {
              uni.showModal({
                  confirmColor: '#eb4b4b',
                  title: '温馨提示',
                  content: "相册调用失败",
                  showCancel: false,
              });
          };
          var success = (info) => {
              console.log('这是相册所得：', info[0]);
              var base64Top = 'data:image/jpeg;base64,'
              setTimeout(() => {
                  that.baseertt(info[0])
              }, 30);

          };
          imp.iCamera.select(option, success, failed);
      },
      baseertt(base64Str) {
          let that = this;
          let format = base64Str.thumbnailUrl.split(".")[1]
          if(['jpg','jpeg','png','bmp','JPG','JPEG','PNG','BMP'].includes(format)){
              console.log('满足条件')
          } else {
              uni.showModal({
                  confirmColor: '#eb4b4b',
                  title: "温馨提示",
                  content: "请上传jpg/jpeg/png/bmp格式的照片",
                  showCancel: false,
              });
              that.scanWorderty = "2";
              return
          }


          let base64Top = 'data:image/jpeg;base64,'
          that.bes64 = base64Top + base64Str.originalData;
          // 图片大小
          const imgFileer = that.showSize(that.bes64);
          console.log("计算的图片大小", imgFileer);
          console.log("计算的图片大小", imgFileer / 1024);
          if (imgFileer > 4096) {
              that.scanWordertytyu = "2";
          }
          // 识别二维码
          const imgFile = that.base642Url(that.bes64);
          qrcode.decode(imgFile);
          qrcode.callback = function (img) {
              if (img == "error decoding QR Code") {
                  uni.showModal({
                      confirmColor: '#eb4b4b',
                      title: "温馨提示",
                      content: "识别二维码失败，请重新选择照片",
                      showCancel: false,
                  });
                  that.scanWorderty = "2";
                  return
              } else {
                  that.scanWord = img
                  console.log("二维码", that.scanWorderty);
              }
          }
          setTimeout(() => {
              //console.log("最终所得",that.bes64,that.scanWord);
              console.log("判断", that.scanWordertytyu, that.scanWorderty);
              if (that.scanWordertytyu == 2) {
                  that.bes64 = "";
              }
              if (that.scanWorderty != 2) {
                  getGPS(that.scanWord, '1', that.scanCodeInfo);
              }
          }, 100);
      },
      //解绑站址
      unbindSite(item) {
          getGPS(item.labelId, '0', this.scanCodeInfo);
      },
      //到货确认，解绑站址
      scanCodeInfo(label, index, latitude, longitude) {
          //到货确认或站址解绑的校验
          let latituder = parseFloat(latitude).toFixed(6);
          let longituder = parseFloat(longitude).toFixed(6);
          const params={
              prjId: this.titleList.prjId,
              labelId: label,
              operatType: index,
              longitude: longituder,
              latitude: latituder
          }
          this.$axios.post('/material/api/cableMateLabel/scanLableCableConfirm',params).then((res)=>{
              this.jumpDetail(res.data,index,latituder,longituder)
          })
      },
      jumpDetail(data,index, latitude, longitude){
          let that=this;
          const dataObj={
              ...data,
              prjId: this.titleList.prjId
          }
          const juLi =data.distance / 1;
          const gdjuLi = data.standardDistance / 1;
          const ref = data.controlModeType;
          if ( juLi <= gdjuLi) {
              that.jumpDetailPage(dataObj,index)
          } else if (ref == 2) {
              uni.showModal({
                  confirmColor: '#eb4b4b',
                  title: "站址经纬度校验",
                  content: `您当前经纬度（WGS84坐标系）为${longitude}，${latitude}，距站址${juLi} m，已超出${gdjuLi} m的最大距离限制。\n是否继续本次到货确认？`,
                  success: (res) => {
                      if(res.confirm){
                          that.jumpDetailPage(dataObj,index)
                      }else{
                          console.log("用户点击否");
                      }
                  },
              });
          } else {
              uni.showModal({
                  confirmColor: '#eb4b4b',
                  showCancel: false,
                  title: "站址经纬度校验",
                  content: `您当前经纬度（WGS84坐标系）为${longitude}，${latitude}，距站址${juLi} m，已超出${gdjuLi} m的限制，暂不允许进行到货确认。\n如需修改站址经纬度，请在资源系统进行修改`,
              });
          }
      },
      jumpDetailPage(data,index){
          if (index == 1) {
              //绑定 1；解绑 0
              uni.navigateTo({
                  url:
                      "../scanOut/detail?item=" +
                      encodeURIComponent(JSON.stringify(data)) +
                      "&flag=2&panduan=1&fushuuser=true&routeType=nonPower&manageMode="+this.manageMode,
              });
          } else {
              uni.navigateTo({
                  url:
                      "../scanOut/detail?item=" +
                      encodeURIComponent(JSON.stringify(data)) +
                      "&flag=3&panduan=1&fushuuser=true&routeType=nonPower&manageMode="+this.manageMode,
              });
          }
      },
      //取消
      canceler(){
          this.bottomShow=false
      }
  }
}
</script>

<style scoped lang="scss">
@import "@/common/common-ui.css";
.collapseStyle {
    background-color: #e6e2e5;
    margin: 5rpx 0;
    padding: 10rpx 0;
}
.unbindLabelStyle {
    padding: 0 0rpx;
    width: 120rpx;
    height: 50rpx;
    font-size: 26rpx;
    text-align: center;
    color: #EB4B4B;
    border: solid 2rpx #EB4B4B;
    border-radius: 10rpx;
}
</style>